package com.taocares.sfss.handler;

import com.taocares.sfss.exception.InternalException;
import com.taocares.sfss.exception.SFSSException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(SFSSException.class)
	public ResponseEntity sfssExceptionHandle(SFSSException exception) {
		log.warn(exception.getMessage());
		Map result = new HashMap();
		result.put("code", exception.getCode());
		result.put("message", exception.getMessage());
		return ResponseEntity.status(exception.getStatus().intValue()).body(result);
	}
	@ExceptionHandler(IOException.class)
	public ResponseEntity ioExceptionHandle(IOException exception) {
		return getMapResponseEntity(exception);
	}
	@ExceptionHandler(InternalException.class)
	public ResponseEntity internalExceptionHandler(InternalException exception) {
		return getMapResponseEntity(exception);
	}
	@ExceptionHandler(RuntimeException.class)
	public ResponseEntity runtimeExceptionHandle(RuntimeException exception) {
		return getMapResponseEntity(exception);
	}

	private ResponseEntity getMapResponseEntity(Exception exception) {
		log.warn("Internal Error, info: {}, exception: {}", exception.getMessage(), exception);
		Map result = new HashMap();
		result.put("code", "InternalError");
		result.put("message", exception.getMessage());
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
	}

}
